#include"Arduino.h"  
#define BUFLEN 16

#define PS_wait 0
#define PS_waitPortInf 1
#define PS_waitLength 2
#define PS_receiving 3
#define PS_ready 4

char ReceiverIndex;
char PortIndex;
unsigned char PortState;
char RxData[BUFLEN];
unsigned char RxLen;
unsigned char CurPoz;
char SBUF;
unsigned char *uSBUF;
unsigned char CheckSum;

void (*OnReceive)(char PortIndex,char *data,unsigned char data_len);

void NullCallback(char PortIndex,char *data,unsigned char data_len)
{
}

void SerialReset()
{
  PortIndex=0;
  RxLen=0;
  CurPoz=0;
  PortState=0;
}

 void SerialInit(int b,char RIndex,void (*Callback)(char PortIndex,char *data,unsigned char data_len))
{
  ReceiverIndex=RIndex;
  PortIndex=0;
  RxLen=0;
  CurPoz=0;
  PortState=0;
  OnReceive=Callback;
  uSBUF = &SBUF;
  Serial.begin(b);
}

void sendchar(char c)
{
  Serial.print(c);
}

void sendstr(char* str)
{
  Serial.print(str);
}

void sendstr(char* str,unsigned char len)
{
  char i=0;
  while(i<len)
  {
    sendchar(str[i]);
    i++;
  }
}

void SerialUpdate()
{
  while(Serial.available()>0)
  {
    SBUF=Serial.read();
    switch (PortState)
    {
      case 0:
        if(SBUF==0x7f)
        {
          PortState=1;  
        }
        break;
      case 1:
        if((SBUF&0x0f)==ReceiverIndex)
        {
          PortState=2;
          PortIndex=SBUF>>4;
        }
        else
        {
          PortState=0;
        }
        break;
      case 2:
        if(SBUF<=BUFLEN)
        {
          RxLen=SBUF;
          PortState=3;
          CheckSum = 0;
        }
        else
        {
          PortIndex=0;
          PortState=0;      
        }
        break;
      case 3:
        if(CurPoz<RxLen)
        {
          RxData[CurPoz]= SBUF;
          CheckSum += *uSBUF;
          CurPoz++;
        }
        else if(*uSBUF==0x7E)
        {
          PortState=4;
          OnReceive(PortIndex,RxData,RxLen);
          SerialReset();
          CurPoz=0;
        }
        else
        {
          PortState=0;
          PortIndex=0;
          CurPoz=0;
          RxLen=0;
        }
        break;  
    }
  }
}

void SendData(char* str,unsigned char len, char Receiver,char Port)
{
  sendchar(0x7f);
  sendchar(Receiver|(Port<<4));
  sendchar(len);
  sendstr(str,len);
  sendchar(0x7e);
}
